//菜单搜索
$(function () {
    $('#sidebar-form').on('submit', function (e) {
        e.preventDefault();
    });

    $('.sidebar-menu li.active').data('lte.pushmenu.active', true);

    $('#search-input').on('keyup', function () {
        var term = $('#search-input').val().trim();

        if (term.length === 0) {
            $('.sidebar-menu li').each(function () {
                $(this).show(0);
                $(this).removeClass('active');
                if ($(this).data('lte.pushmenu.active')) {
                    $(this).addClass('active');
                }
            });
            return;
        }

        $('.sidebar-menu li').each(function () {
            if ($(this).text().toLowerCase().indexOf(term.toLowerCase()) === -1) {
                $(this).hide(0);
                $(this).removeClass('pushmenu-search-found', false);

                if ($(this).is('.treeview')) {
                    $(this).removeClass('active');
                }
            } else {
                $(this).show(0);
                $(this).addClass('pushmenu-search-found');

                if ($(this).is('.treeview')) {
                    $(this).addClass('active');
                }

                var parent = $(this).parents('li').first();
                if (parent.is('.treeview')) {
                    parent.show(0);
                }
            }

            if ($(this).is('.header')) {
                $(this).show();
            }
        });

        $('.sidebar-menu li.pushmenu-search-found.treeview').each(function () {
            $(this).find('.pushmenu-search-found').show(0);
        });
    });
});

/* 清除搜索表单 */
function clearSearchForm() {
    let url_all = window.location.href;
    let arr = url_all.split('?');
    let url = arr[0];
    window.location.href = url;

}
window.rootPath = (function (src) {
    src = document.scripts[document.scripts.length - 1].src;
    return src.substring(0, src.lastIndexOf("/") + 1);
})();


layui.config({
    dir: rootPath + '../plugins/layui/',
    base: rootPath + '../plugins/layui/module/',
    version: true
}).extend({
    treeTable: "treeTable/treeTable",
    iconPickerFa: "iconPicker/iconPickerFa",
    layNumber: "layNumber/layNumber",
    croppers: "cropper/js/croppers",
    inputTags: "inputTags/inputTags",
    fileManager: "filemanage/fileManager",
    layFile: "layFile/layFile",
    "okTab": "okmodules/okTab",
    "okCountUp": "okmodules/okCountUp",
    "okUtils": "okmodules/okUtils",
    "okFly": "okmodules/okFly",
    "okGVerify": "okmodules/okGVerify",
    "qrcode": "okmodules/qrcode",
    "okQrcode": "okmodules/okQrcode",
    "okAddlink": "okmodules/okAddlink",
    "okLayer": "okmodules/okLayer",
    "okMock": "okmodules/okMock",
    "okContextMenu": "okmodules/okContextMenu",
    "okCookie": "okmodules/okCookie",
    "okMd5": "okmodules/okMd5",
    "okToastr": "okmodules/okToastr",
    "okBarcode": "okmodules/okBarcode",
    "okNprogress": "okmodules/okNprogress",
    "okSweetAlert2": "okmodules/okSweetAlert2",
    "okHoliday": "okmodules/okHoliday",
    "okLayx": "okmodules/okLayx",
    "jqprint": "okmodules/jqprint",
}).use(['form', 'layer', 'jquery', 'table', 'element', 'layNumber'], function () {
    var $ = layui.jquery,
        form = layui.form,
        layer = layui.layer,
        table = layui.table,
        element = layui.element;

    form.verify({
        nikename: function (value) {
            if (value.length < 5) {
                return '昵称至少得5个字符啊';
            }
        },
        pass: [/(.+){6,12}$/, '密码必须6到12位'],
        repass: function (value) {
            if (value != $("input[name='password']").val()) {
                return '两次密码不一致';
            }
        },
        ip: function (value, item) {
            function isValidIP(ip) {
                var reg = /(^$)|^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
                return reg.test(ip);
            }
            if (isValidIP(value) == false) {
                return '请输入正确的IP地址';
            }
        }
    });
    var layNumber = layui.layNumber;
    layNumber.plusminus();
    form.on('submit(submit)', function (data) {
        let loadT = layer.msg('正在提交，请稍候…', {
            icon: 16,
            time: 0,
            shade: [0.3, "#000"],
            scrollbar: false,
        });
        if (adminDebug) {
            console.log('%cajax submit start!', ';color:#333333');
            console.log('action:' + data.form.action);
            console.log('method:' + data.form.method);
            console.log('data:' + JSON.stringify(data.field));
        }

        $.ajax({
            url: data.form.action,
            dataType: 'json',
            type: data.form.method,
            data: data.field,
            success: function (result) {
                layer.close(loadT);
                layer.msg(result.msg, {
                    icon: result.code === 200 ? 1 : 2,
                    scrollbar: false,
                });

                if (adminDebug) {
                    console.log('request success!');
                    if (result.code === 200) {
                        console.log('%cresult success', ';color:#00a65a');
                    } else {
                        go = 'url://current';
                        console.log('%cresult fail', ';color:#f39c12');
                    }
                }
                goUrl(result.url);
            },
            error: function (xhr, type, errorThrown) {
                //异常处理；
                if (adminDebug) {
                    console.log('%csubmit fail!', ';color:#dd4b39');
                    console.log();
                    console.log("type:" + type + ",readyState:" + xhr.readyState + ",status:" + xhr.status);
                    console.log("url:" + data.form.action);
                    console.log("data:" + data.field);
                }
                layer.close(loadT);

                layer.msg(xhr.responseJSON.message, {
                    icon: 2,
                    scrollbar: false,
                });
            }
        });
        return false;

    });
    // 监听全选
    form.on('checkbox(checkall)', function (data) {

        if (data.elem.checked) {
            $('tbody input[type=checkbox]').prop('checked', true);
        } else {
            $('tbody input[type=checkbox]').prop('checked', false);
        }
        form.render('checkbox');

    });

    // 放大图片
    $('.photosimg').off('click').click(function () {
        var src = $(this).attr('src'),
            alt = $(this).attr('alt');
        var photos = {
            "id": Math.random(),
            "data": [{
                "alt": alt,
                "pid": Math.random(),
                "src": src,
                "thumb": src
            }]
        };
        layer.photos({
            photos: photos,
            anim: 5
        });
        return false;
    });

    // 放大一组图片
    $('body').off('click').on('click', '.dataListImg', function () {
        var doms = $(this).parent(".dataListMultiImg").find('img'),
            // 被点击的图片地址
            now_src = $(this).attr('src'),
            alt = $(this).attr('alt'),
            data = [];
        $.each(doms, function (key, value) {
            var src = $(value).attr('src');
            if (src != now_src) {
                // 压入其他图片地址
                data.push({
                    "alt": alt,
                    "pid": Math.random(),
                    "src": src,
                    "thumb": src
                });
            } else {
                // 把当前图片插入到头部
                data.unshift({
                    "alt": alt,
                    "pid": Math.random(),
                    "src": now_src,
                    "thumb": now_src
                });
            }
        });
        var photos = {
            "id": Math.random(),
            "data": data,
        };
        layer.photos({
            photos: photos,
            anim: 5
        });
        return false;
    });


});

/** 跳转到指定url */
function goUrl(url = 1) {
    console.log(url);
    //清除列表页选择的ID
    if (url !== 'url://current' && url !== 1) {
        dataSelectIds = [];
    }
    if (url === 'url://current' || url === 1) {
        console.log('Stay current page.');
    } else if (url === 'url://reload' || url === 2) {
        console.log('Reload current page.');
        window.location.reload();
    } else if (url === 'url://back' || url === 3) {
        console.log('Return to the last page.');
        history.back(1);
    } else if (url === 4 || url === 'url://close-refresh') {
        console.log('Close this layer page and refresh parent page.');
        let indexWindow = parent.layer.getFrameIndex(window.name);
        //先刷新父级页面
        parent.goUrl(2);
        //再关闭当前layer弹窗
        parent.layer.close(indexWindow);
    } else if (url === 5 || url === 'url://close-layer') {
        console.log('Close this layer page.');
        let indexWindow = parent.layer.getFrameIndex(window.name);
        parent.layer.close(indexWindow);
    } else {
        console.log('Go to ' + url);
        window.location.href = url;

    }
}

/**
 * ajax访问按钮
 * 例如元素为<a class="AjaxButton" data-confirm="1" data-type="1" data-url="disable" data-id="2" data-go="" ></a>
 * data-confirm为是否弹出提示，1为是，2为否。比如删除某条数据，data-confirm="1"就会弹出来提示
 * data-type为访问方式，1为直接ajax访问，例如删除操作。2是为打开layer窗口展示数据，例如查看操作日志详情
 * data-url为要访问的url
 * data-id为要操作的数据ID，可以填写正常的数据ID，例如data-id="2"，
 * 或者填写checked表示获取当前数据列表选择的ID，也就是取的变量dataSelectIds的值
 * data-go为操作完成后的跳转url，不设置此参数默认根据后台返回的url跳转
 * data-confirm-title为确认提示弹窗的标题 例如data-confirm-title="删除警告"
 * data-confirm-content为确认提示的内容 例如data-confirm-content="您确定要删除此数据吗？"
 * data-title 窗口显示的标题
 *
 */
$(function () {
    $(document).on('click', '.AjaxButton', function (event) {
        event.preventDefault();

        if (adminDebug) {
            console.log('AjaxButton clicked.');
        }
        //是否弹出提示
        var layerConfirm = $(this).data("confirm") || 1;
        //访问方式，1为直接访问，2为layer窗口显示
        var layerType = parseInt($(this).data("type") || 1);
        //访问的url
        var url = $(this).data("url");
        //访问方式，默认post
        var layerMethod = $(this).data("method") || 'post';
        //访问成功后跳转的页面，不设置此参数默认根据后台返回的url跳转
        var go = $(this).data("go") || 'url://reload';

        //当为窗口显示时可定义宽度和高度
        var layerWith = $(this).data("width") || '80%';
        var layerHeight = $(this).data("height") || '60%';

        //窗口的标题
        var layerTitle = $(this).data('title');

        //当前操作数据的ID
        var dataId = $(this).data("id");
        
        //如果没有定义ID去查询data-data属性
        if (dataId === undefined) {
            var dataData = $(this).data("data") || {};
        } else {
            if (dataId === 'checked') {
                checkboxIds();
                if (dataSelectIds.length === 0) {
                    layer.msg('请选择要操作的数据', {
                        icon: 2,
                        scrollbar: false,
                    });
                    return false;
                }
                dataId = dataSelectIds;
            }
            dataData = {
                "id": dataId
            };
        }

        if (typeof (dataData) != 'object') {
            dataData = JSON.parse(dataData);
        }
        /*需要确认操作*/
        if (parseInt(layerConfirm) === 1) {
            //提示窗口的标题
            var confirmTitle = $(this).data("confirmTitle") || '操作确认';
            //提示窗口的内容
            var confirmContent = $(this).data("confirmContent") || '您确定要执行此操作吗?';
            layer.confirm(confirmContent, {
                title: confirmTitle,
                closeBtn: 1,
                icon: 3
            }, function () {
                //如果为直接访问
                if (layerType === 1) {
                    ajaxRequest({
                        host: url,
                        method: layerMethod,
                        data: dataData,
                        success: function (result) {
                            layer.msg(result.msg, {
                                icon: result.code ? 1 : 2,
                                time: 500,
                                scrollbar: false,
                            }, function () {
                                goUrl(go);

                            });
                        }
                    });
                } else if (layerType === 2) {
                    //如果为打开窗口
                    //先进行权限查询
                    if (checkAuth(url)) {
                        layer.open({
                            type: 1,
                            area: [layerWith, layerHeight],
                            title: layerTitle,
                            shadeClose: true,
                            closeBtn: 1,
                            content: url + "?request_type=layer_open&" + parseParam(dataData),
                            scrollbar: false,
                        });
                    }
                }
            });
        } else {
            //不需要操作确认
            if (layerType === 1) {

                //直接请求
                ajaxRequest({
                    host: url,
                    method: layerMethod,
                    data: dataData,
                    success: function (result) {
                        layer.msg(result.msg, {
                            icon: result.code ? 1 : 2,
                            time: 500,
                            scrollbar: false,
                        }, function () {
                            goUrl(go);

                        });
                    }
                });
            } else if (layerType === 2) {
                //弹出窗口
                //检查权限
                if (checkAuth(url)) {
                    //用窗口打开
                    layer.open({
                        type: 2,
                        area: [layerWith, layerHeight],
                        title: layerTitle,
                        shadeClose: true,
                        closeBtn: 1,
                        content: url + "?request_type=layer_open&" + parseParam(dataData),
                        scrollbar: false,
                    });
                }
            }
        }
    });
});


function checkboxIds() {
    $('tbody input[type=checkbox]').each(function (index, el) {
        if ($(this).prop('checked')) {
            dataSelectIds.push($(this).val())
        }
    });
}
//ajax请求封装
/**
 *
 * @param host 访问的url 
 * @param method  访问方式
 * @param data  data数据
 * @param success 成功回调
 * @param error 成功回调
 * @param complete 
 */
function ajaxRequest(param) {

    var defaultFun = function (result) {
        console.log(result);
    }
    let host = param.host; // 请求地址
    let searchDomin = new RegExp('http|https');
    let url = searchDomin.test(host) ? host : window.location.origin + '/' + host; //真实请求地址
    let method = param.method; //请求方法
    let data = param.data; //请求参数
    let success = param.hasOwnProperty("success") ? param.success : defaultFun; //成功回调
    let error = param.hasOwnProperty("error") ? param.error : defaultFun; //失败回调
    let complete = param.hasOwnProperty("complete") ? param.complete : defaultFun; //失败回调

    $.ajax({
        url: url,
        dataType: 'json',
        type: method,
        data: data,
        success: function (result) {

            return success(result);

        },
        error: function (xhr, type, errorThrown) {
            //异常处理；
            // if (adminDebug) {
            console.log('%crequest fail!', ';color:#dd4b39');
            console.log();
            console.log("type:" + type + ",readyState:" + xhr.readyState + ",status:" + xhr.status);
            console.log("url:" + url);
            console.log("data:");
            console.log(data);

            return error(xhr);
        },
        complete: function (xhr, type, errorThrown) {
            return complete(type);
        }
    });
}
//改变每页数量
function changePerPage(obj) {
    if (adminDebug) {
        console.log('当前每页数量' + Cookies.get(cookiePrefix + 'admin_per_page'));
    }
    Cookies.set(cookiePrefix + 'admin_per_page', obj.value, {
        expires: 30
    });
    window.location.reload();

}

function reload() {
    $(".page-content .layui-show").find("iframe")[0].contentWindow.location.reload(true);

}
/**
 * 检查授权
 */
function checkAuth(url) {
    var hasAuth = false;
    var loadT = layer.msg('正在请求,请稍候…', {
        icon: 16,
        time: 0,
        shade: [0.3, '#000'],
        scrollbar: false,
    });
    $.post({
        url: url,
        data: {
            "check_auth": 1
        },
        dataType: 'json',
        async: false,
        success: function (result) {
            layer.close(loadT);
            hasAuth = true;
        },
        error: function (xhr, type, errorThrown) {
            layer.msg('访问错误,代码' + xhr.status, {
                icon: 2,
                scrollbar: false,
            });
        }
    });
    return hasAuth;
}

/** 处理url参数 **/
function parseParam(param, key) {
    var paramStr = "";
    if (param instanceof String || param instanceof Number || param instanceof Boolean) {
        paramStr += "&" + key + "=" + encodeURIComponent(param);
    } else {
        $.each(param, function (i) {
            var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i);
            paramStr += '&' + parseParam(this, k);
        });
    }
    return paramStr.substr(1);
}

/** 导出excel **/
function exportData(url) {


    let exportUrl = url || window.location.href;
    // var openUrl = exportUrl + '?export_data=1&' + $("#searchForm").serialize();

    if (window.location.search == '') {
        exportUrl += '?export_data=1';
    } else {
        exportUrl += '&export_data=1';
    }
    window.open(exportUrl);
}

function setCookie(a, c) {
    var b = 30;
    var d = new Date();
    d.setTime(d.getTime() + b * 24 * 60 * 60 * 1000);
    document.cookie = a + "=" + escape(c) + ";expires=" + d.toGMTString()
}

function getCookie(b) {
    var a, c = new RegExp("(^| )" + b + "=([^;]*)(;|$)");
    if (a = document.cookie.match(c)) {
        return unescape(a[2])
    } else {
        return null
    }
}
/**
 * 刷新token
 */
function refreshToken() {
    ajaxRequest({
        host: '/admin/auth/refreshToken',
        method: 'post',
        success: function (res) {
            $("[name='__token__']").val(res.data.token);
        }
    })
}



function SafeMessage(j, h, g, f) {
    if (f == undefined) {
        f = ""
    }
    var d = Math.round(Math.random() * 9 + 1);
    var c = Math.round(Math.random() * 9 + 1);
    var e = "";
    e = d + c;
    sumtext = d + " + " + c;
    setCookie("vcodesum", e);
    var mess = layer.open({
        type: 1,
        title: j,
        area: "350px",
        closeBtn: 2,
        shadeClose: true,
        content: "<div class='bt-form webDelete pd20 pb70'><p>" + h + "</p>" + f + "<div class='vcode'>" + lan.bt.cal_msg + "<span class='text'>" + sumtext + "</span>=<input type='number' id='vcodeResult' value=''></div><div class='bt-form-submit-btn'><button type='button' class='btn btn-danger btn-sm bt-cancel'>" + lan.public.cancel + "</button> <button type='button' id='toSubmit' class='btn btn-success btn-sm' >" + lan.public.ok + "</button></div></div>"
    });
    $("#vcodeResult").focus().keyup(function (a) {
        if (a.keyCode == 13) {
            $("#toSubmit").click()
        }
    });
    $(".bt-cancel").click(function () {
        layer.close(mess);
    });
    $("#toSubmit").click(function () {
        var a = $("#vcodeResult").val().replace(/ /g, "");
        if (a == undefined || a == "") {
            layer.msg('请正确输入计算结果!');
            return
        }
        if (a != getCookie("vcodesum")) {
            layer.msg('请正确输入计算结果!');
            return
        }
        layer.close(mess);
        g();
    })
}